<!--  -->
<template>
  <div class="repertory-label-data-table">
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column
        prop="name"
        label="标签名"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        label="类型"
      >
        <template slot-scope="scope">
          <span
            class="orange"
            v-if="scope.row.type > 0"
          >系统默认</span>
          <span v-else>用户自定义</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="summary"
        label="统计"
      >
        <template slot-scope="scope">
          <span>资源总数：{{scope.row.summary}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createAt"
        label="创建时间"
      >
        <template slot-scope="scope">
          <span>{{scope.row.createAt | dateformat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            @click="editorLabelName(scope.row.id)"
            type="text"
            size="small"
          >修改名称</el-button>
          <el-button
            @click="deleteLabel(scope.row.id)"
            type="text"
            size="small"
            :disabled="scope.row.type > 0"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改名称 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="490px"
      @closed="closed"
      :close-on-click-modal="false"
    >
      <el-form
        :model="currentRepertoryLabel"
        v-loading="labelLoading"
        :rules="rules"
        ref="labelSave"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item
          label="标签名称"
          prop="name"
        >
          <el-input
            v-model.trim="currentRepertoryLabel.name"
            autocomplete="off"
            size="medium"
            style="width: 370px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button size="small" @click="closed">取 消</el-button>
        <el-button size="small" type="primary" @click="submitEditLabelName">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.$post('/repertory/all-label-for-tabledata', null).then((response) => {
      if (response && response.length > 0) {
        this.tableData = initTableData(response)
      } else {
        this.tableData = []
      }
      this.loading = false
    })
  },
  data () {
    var checkIshas = (rule, value, callback) => {
      let bool = true
      this.tableData.map(item => {
        if (item.id !== this.currentRepertoryLabel.id) {
          if (value === item.name) {
            bool = false
          }
        }
      })
      if (!bool) {
        callback(new Error('标签名称已存在'))
      } else {
        return callback()
      }
    }
    return {
      // 初始化加载
      loading: true,
      // 表格展示的数据
      tableData: [],
      // 弹出对话框
      dialogFormVisible: false,
      // 对话框加载
      labelLoading: false,
      // 当前数据
      currentRepertoryLabel: {},
      // 对话框 title
      title: '',
      rules: {
        name: [
          { required: true, message: '请输入标签名', trigger: 'blur' },
          { min: 1, max: 100, message: '标签名长度不能大于100个字符', trigger: 'blur' },
          { validator: checkIshas, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 新建
    create () {
      this.title = '新建标签'
      this.currentRepertoryLabel = {
        id: 0,
        name: ''
      }
      this.dialogFormVisible = true
    },
    editorLabelName (id) {
      let item = getItem(id, this.tableData)
      if (!item) {
        return
      }
      this.title = '编辑标签名称'
      this.currentRepertoryLabel = JSON.parse(JSON.stringify(item))
      this.dialogFormVisible = true
    },
    submitEditLabelName () {
      // if (this.tableData.length > 7 && this.currentRepertoryLabel.id === 0) {
      //   this.$message.error('标签数量最多8个，已达上限！')
      //   return
      // }
      this.$refs['labelSave'].validate((valid) => {
        if (valid) {
          let param = {
            id: this.currentRepertoryLabel.id,
            name: this.currentRepertoryLabel.name
          }
          this.labelLoading = true
          this.$post('/repertory/label-save', param).then((response) => {
            if (response && response.id) {
              this.tableData = JSON.parse(JSON.stringify(resetTableData(response, this.tableData)))
              this.dialogFormVisible = false
              this.title = ''
              this.currentRepertoryLabel = {}
            }
            this.labelLoading = false
          })
        } else {
          return false
        }
      })
    },
    // 删除
    deleteLabel (id) {
      let item = getItem(id, this.tableData)
      if (!item) {
        return
      }
      let param = {
        id: id
      }
      this.$confirm('确认删除 ' + item.name + '？', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        this.$post('/repertory/label-delete', param).then((response) => {
          if (response && response.id) {
            this.tableData = deleteTableData(response, this.tableData)
            this.dialogFormVisible = false
            this.title = ''
            this.currentRepertoryLabel = {}
          }
          this.labelLoading = false
        })
      }).catch(() => {
      })
    },
    // 关闭
    closed () {
      this.$refs['labelSave'].clearValidate()
      this.labelLoading = false
      this.dialogFormVisible = false
    }
  }
}

function deleteTableData (data, list) {
  return list.filter((item) => {
    return item.id !== data.id
  })
}

function resetTableData (data, list) {
  let bool = false
  for (let i in list) {
    if (list[i].id === data.id) {
      bool = true
      list[i].name = data.name
      break
    }
  }
  if (!bool) {
    list.push({
      id: data.id,
      name: data.name,
      type: data.type,
      summary: 0,
      createAt: data.createAt
    })
  }
  return list
}

function initTableData (data) {
  return data
}

function getItem (id, list) {
  let ite = list.find((item) => {
    return item.id === id
  })
  return ite
}

</script>

<style scoped>
.repertory-label-data-table .el-form-item {
  margin-bottom: 0;
}
.repertory-label-data-table /deep/ .el-table th {
  color: #555;
}
</style>
